<?php
namespace Api\Controller;
use Think\Controller;
class MailController extends Controller {

    /**
     * 查询邮件列表
     */
    public function mail_list() {
        $offset = intval(I('get.offset'));
        $limit = intval(I('get.limit'));
        $order = strtoupper(I('get.order'));

        $retMails = array();

        // 查询邮件
        $sql = sprintf('SELECT id, cmd_data, state, time FROM gm_cmds WHERE cmd_id = %d ORDER BY id %s LIMIT %d OFFSET %d;'
            , GM_CMD_SEND_MAIL, $order, $limit, $offset);

        $model = M();
        $model->db(2, "DB_WORLD");

        $orginMailList = $model->query($sql);
        $mailList = array();
        $charaIdMap = array();
        foreach ($orginMailList as &$orginMail) {
            $mailObj = json_decode($orginMail['cmd_data'], true);

            $stateDesc = '';
            switch ($orginMail['state']) {
                case GM_CMD_STATE_READY: $stateDesc = '准备处理'; break;
                case GM_CMD_STATE_PROCESSING: $stateDesc = '处理中'; break;
                case GM_CMD_STATE_PROCESSED: $stateDesc = '已处理'; break;
                case GM_CMD_STATE_DATA_ERROR: $stateDesc = '数据错误'; break;
                case GM_CMD_STATE_PROCESS_ERR: $stateDesc = '处理出错'; break;
                case GM_CMD_STATE_UNKNOWN_CMD: $stateDesc = '未知命令'; break;
                case GM_MAIL_STATE_MAIN_FULL: $stateDesc = '收件人邮箱已满'; break;
                case GM_MAIL_STATE_NO_RECEIVER: $stateDesc = '没有找到收件人'; break;
            }

            $retMail = array(
                'id'        => $orginMail['id'],
                'receiver'  => $mailObj['receiver'],
                'subject'   => $mailObj['subject'],
                'body'      => $mailObj['body'],
                'money'     => $mailObj['money'] / 10000,
                'state'     => $stateDesc,
                'time'      => $orginMail['time']
            );
            array_push($mailList, $retMail);
            $charaIdMap[$mailObj['receiver']] = 1;
        }

        // 查询角色名
        if (count($charaIdMap) > 0) {
            $model->db(1, "DB_CHARACTERS");
            $charaNames = $model->query(sprintf('SELECT guid, name FROM characters WHERE guid in (%s);',
                implode(',' ,array_keys($charaIdMap))));
            $guid2name = array();
            foreach ($charaNames as &$charName) {
                $guid2name[$charName['guid']] = $charName['name'];
            }
            foreach ($mailList as &$mail) {
                $mail['receiver'] = $guid2name[$mail['receiver']];
            }
        }

        // 查询邮件数量
        $model->db(2, "DB_WORLD");
        $mailCount = $model->query(sprintf('SELECT COUNT(id) AS mail_count FROM gm_cmds WHERE cmd_id = %d;',
            GM_CMD_SEND_MAIL));

        echo json_encode(array(
            'rows'  => $mailList,
            'total'   => $mailCount[0]['mail_count']
        ));
    }

    /**
     * 发送邮件
     */
    public function send_mail() {
        $resp = array(
            'code'  => 0,
            'desc'  => '',
            'data'  => array(),
        );

        do {
            $guid       = intval(I('post.guid'));
            $subject    = I('subject');
            $body       = I('body');
            $money      = intval(I('money'));
            $itemGuid   = intval(I('item_guid'));
            $itemCount   = intval(I('item_count'));

            if (empty($body) || empty($subject)) {
                $resp['code'] = 1; $resp['desc'] = '必须输入邮件标题和内容';
                break;
            }

            $cmd_id = GM_CMD_SEND_MAIL;

            $model = M();
            if ($guid == 0) {
                // 给服务器所有角色发邮件
                $model->db(1, "DB_CHARACTERS");
                $charaIds = $model->query('SELECT guid from characters;');
                $model->db(2, "DB_WORLD");
                foreach($charaIds as $chara) {
                    $mailStr = formatMail(intval($chara['guid']), $subject, $body, $money, $itemGuid, $itemCount);
                    if ($model->execute("INSERT INTO gm_cmds values (0, $cmd_id, '$mailStr', 0, CURRENT_TIMESTAMP);") == false) {
                        $resp['data'][$charaId] = $model->getDbError();
                    }
                }
            } else {
                // 给单个角色发邮件
                $model->db(2, "DB_WORLD");
                $mailStr = formatMail($guid, $subject, $body, $money, $itemGuid, $itemCount);
                if ($model->execute("INSERT INTO gm_cmds values (0, $cmd_id, '$mailStr', 0, CURRENT_TIMESTAMP);") == false) {
                    $resp['code'] = 1; $resp['desc'] = $model->getDbError();
                }
            }
        } while (false);
        $this->ajaxReturn($resp, 'json');
    }
}